package com.xiaomi.shwx.interceptor;

import com.xiaomi.shwx.common.util.BaseContext;
import com.xiaomi.shwx.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author lei
 * @description
 * @date 2024/5/22 19:25
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("进入拦截器------");
        // 判断当前拦截到的是Controller方法还是其他资源
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 1、从请求头中获取令牌
        String token = request.getHeader("token");
        // 2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.checkToken(token);
            Long userId = Long.valueOf(claims.get("userId").toString());
            // 将用户id存储到ThreadLocal中
            BaseContext.setCurrentId(userId);
            return true;
        }catch (Exception e){
            response.setStatus(401);
            return false;
        }
    }
}
